package action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import common.ExcelTools;
import table.User;

/**
 * 处理上传的Excel的控制器
 */
@WebServlet("/UserExcelUpload")
public class UserExcelUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserExcelUpload() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 使用get访问该页无效
		response.getWriter().append("Please use POST method!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 管理员登录有效性验证段
		User user = (User) request.getSession().getAttribute("user");
		if(user == null || !user.getGroup().equals("admin")){
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		
		String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
		File file = new File(savePath);
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("创建目录：" + savePath);
			file.mkdir();
		}
		String savedFileName = null;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			upload.setSizeMax(1024 * 1024 * 2); // 设置上传文件总大小不能超过2mb
			if (!ServletFileUpload.isMultipartContent(request)) {
				return;
			}
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString("UTF-8");
					System.out.println(name + "=" + value);
				} else {
					String filename = item.getName();
					System.out.println(filename);
					if (filename == null || filename.trim().equals("")) {
						continue;
					}
					filename = filename.substring(filename.lastIndexOf("\\") + 1);
					InputStream in = item.getInputStream();
					savedFileName = savePath + "\\" + System.nanoTime() + "-" + filename;
					System.out.println("File save as : " + savedFileName);
					FileOutputStream out = new FileOutputStream(savedFileName);
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = in.read(buffer)) > 0) {
						out.write(buffer, 0, len);
					}
					in.close();
					out.close();
					item.delete();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			savedFileName = null;
		}
		
		if(savedFileName != null) {
			// 读取上传的excel中的内容
			File sf = new File(savedFileName);
			List<User> ulist = ExcelTools.readUsersFromExcel(sf);
			for(User u:ulist)
				System.out.println(u);
			
			request.setAttribute("userlist", ulist);
			request.getRequestDispatcher("admin_user_add.jsp?mode=1").forward(request, response);
		}
	}

}
